package com.assessment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.assessment.entity.Arole;
import com.assessment.entity.Atype;
import com.assessment.entity.Column;
import com.assessment.mapper.AtypeMapper;
import com.assessment.service.AtypeService;
import com.assessment.vo.AtypeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty;
import static org.apache.coyote.http11.Constants.a;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 鑫十一
 * @since 2021-12-15
 */
@Service
@Transactional
public class AtypeServiceImpl extends ServiceImpl<AtypeMapper, Atype> implements AtypeService {
    @Override
    public List<Column> getColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("打分方式名").setProp("name"));
        columns.add(new Column().setLabel("分数等级个数").setProp("num"));
        return columns;
    }

    @Override
    public boolean saveVo(AtypeVo item) {
        if (item.getTypeArr().size() != Integer.parseInt(item.getNum())){
            return false;
        }
        if (item.getTypeArr().size() > 1) {
            String scores = "";
            String snames = "";
            String maxnums = "";
            for (Atype atype : item.getTypeArr()) {
                snames += atype.getSname() + ',';
                scores += atype.getScore() + ',';
                maxnums += atype.getMaxnum() + ',';
            }
            item.setSname(snames);
            item.setScore(scores);
            item.setMaxnum(maxnums);
        }
        this.save(item);
        return false;
    }

    @Override
    public List<AtypeVo> getVoList(String item) {
        QueryWrapper<Atype> queryWrapper = new QueryWrapper<>();
        if (item != null) {
            JSONObject jsonObject = JSON.parseObject(item);
            if (!isEmpty(jsonObject.get("name"))) {
                queryWrapper.like("name", jsonObject.get("name"));
            }
        }
        List<Atype> list = this.list(queryWrapper); // 查到的结果
        List<AtypeVo> atypeVos = new ArrayList<>();
        list.forEach(atype -> {
            AtypeVo atypeVo = (AtypeVo) atype;
            String[] scores = atype.getScore().split(",");
            String[] snames = atype.getSname().split(",");
            String[] maxnum = atype.getMaxnum().split(",");
            for (int i = 0; i < scores.length; i++) {
                atypeVo.getTypeArr().add(new Atype().setScore(scores[i]).setSname(snames[i]).setMaxnum(maxnum[i]));
            }
            atypeVos.add(atypeVo);
        });
        return atypeVos;
    }
}
